/*
 * $Id$
 * Copyright (C) 2009 Sharp Corp. Corporate Research and Development Group.
 */
package com.liwen.mywebview;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.webkit.HttpAuthHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.TextSize;

/**
 * store web view class.
 */
public class StoreWebView extends WebView {
    /**
     * PageStateListener list.
     */
    private ArrayList<PageStateListener> mPageStateListenerList
                                        = new ArrayList<PageStateListener>();
    /**
     * web settings.
     */
    private WebSettings webSettings = null;
    
    /**
     * url.
     */
    private String mUrl = "";
    /**
     * on layout flag.
     */
    private boolean mIsLayout = false;
    
    Context context;

    /**
     * Constructs a new instance of StoreWebView with the specified context.
     *
     * @param context
     *            Context
     */
    public StoreWebView(Context context) {
        this(context, null);
        this.context = context;
        
    }

    /**
     * Constructs a new instance of StoreWebView with the specified context and
     * attributes.
     *
     * @param context Context
     * @param attrs AttributeSet
     */
    public StoreWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setWebChromeClient(mWebChromeClient);
        this.setWebViewClient(mWebViewClient);
        this.setVerticalScrollbarOverlay(true);
        webSettings = this.getSettings();
        webSettings.setNeedInitialFocus(false);
        webSettings.setSavePassword(false);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        webSettings.setUserAgentString("StoreApp/" + Build.ID + " (" + Build.MODEL + ")");
        DisplayMetrics dm = new DisplayMetrics(); 
        ((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(dm);
        // will either be DENSITY_LOW, DENSITY_MEDIUM or DENSITY_HIGH 
        int dpiClassification = dm.densityDpi; 
        // these will return the actual dpi horizontally and vertically 
        float xDpi = dm.xdpi; 
        float yDpi = dm.ydpi; 
        Log.d("liwen", "xDpi:"+xDpi);
        Log.d("liwen", "yDpi:"+yDpi);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
//        webSettings.setUseWideViewPort(true);
//        webSettings.setLoadWithOverviewMode(true);
//        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    }



    /**
     * Callbacks for page state.
     */
    public interface PageStateListener {
        /**
         * Notify the application that a page has started loading.
         *
         * @param url The url of the page.
         */
        void onPageStarted(String url);
        /**
         * Tell the application the current progress of loading a page.
         *
         * @param newProgress
         *            Current page loading progress,represented by an integer
         *            between 0 and 100.
         */
        void onProgressChanged(int newProgress);
        /**
         * Notify the application that a page has finished loading.
         *
         * @param url The url of the page.
         */
        void onPageFinished(String url);
        /**
         * This is called during layout when the size of this view has changed.
         *
         * @param w Current width of this view.
         * @param h Current height of this view.
         * @param ow Old width of this view.
         * @param oh Old height of this view. 
         */
        void onPageViewSizeChanged(int w, int h, int ow, int oh);
        /**
         * Give the host application a chance to take over the control when a
         * new url is about to be loaded in the current WebView.
         *
         * @param view web view.
         * @param url  tag url.
         * @return boolean false:load in store. true:load in browser.
         */
        boolean shouldOverrideUrlLoading(WebView view, String url);
        /**
         * Displays SSL error(s) dialog to the user.
         */
//        void onReceivedSslError(final WebView view, final SslErrorHandler handler,
//                final SslError error);
    }

//    @Override
//    public boolean onTouchEvent(MotionEvent ev) {
//        if(ev.getAction() == MotionEvent.ACTION_DOWN) {
//            this.showScrollbar();
//        }
//        return super.onTouchEvent(ev);
//    }

    /**
     * Add a PageStateListener to PageStateListener list.
     *
     * @param pageStateListener page state listener.
     */
    public void addPageStateListener(PageStateListener pageStateListener) {
        if (pageStateListener == null) {
            return;
        }
        this.mPageStateListenerList.add(pageStateListener);
    }

    /**
     * the webViewClient implement.
     */
    private WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public void onReceivedHttpAuthRequest(WebView view,
                final HttpAuthHandler handler, final String host, final String realm) {
            
            Log.d(">>>>><<<", "<<<<<<<host>>>>>>>>"+host);
            Log.d(">>>>><<<", "<<<<<<<realm>>>>>>>>"+realm);
//            mWebView.setHttpAuthUsernamePassword(host, realm, "liwen", "LiWen_29");
            handler.proceed("liwen", "LiWen_29");
        }
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d(">>>>><<<", "<<<<<<<onPageStarted>>>>>>>>");
            super.onPageStarted(view, url, favicon);
//            for (PageStateListener pageStateListener : mPageStateListenerList) {
//                pageStateListener.onPageStarted(url);
//            }
        }

//        @Override
//        public void onPageFinished(WebView view, String url) {
//            super.onPageFinished(view, url);
//            for (PageStateListener pageStateListener : mPageStateListenerList) {
//                pageStateListener.onPageFinished(url);
//            }
//        }
//
//        @Override
//        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            boolean isBrowser = false;
//            for (PageStateListener pageStateListener : mPageStateListenerList) {
//                isBrowser = pageStateListener.shouldOverrideUrlLoading(view, url);
//            }
//            if(isBrowser) {
//                return true;
//            } else {
//                return super.shouldOverrideUrlLoading(view, url);
//            }
//        }

        /**
         * Displays SSL error(s) dialog to the user.
         */
//        public void onReceivedSslError(final WebView view, final SslErrorHandler handler,
//                final SslError error) {
//
//            StringBuffer sslError = new StringBuffer("There are problems with the security certificate for this site." + "\n\n");
//            if (error.hasError(SslError.SSL_UNTRUSTED)) {
//                sslError.append("This certificate is not from a trusted authority." + "\n");
//            }
//            if (error.hasError(SslError.SSL_IDMISMATCH)) {
//                sslError.append("The name of the site does not match the name on the certificate." + "\n");
//            }
//            if (error.hasError(SslError.SSL_EXPIRED)) {
//                sslError.append("This certificate has expired." + "\n");
//            }
//            if (error.hasError(SslError.SSL_NOTYETVALID)) {
//                sslError.append("This certificate is not valid yet." + "\n");
//            }
//            new AlertDialog.Builder(context)
//                    .setIcon(android.R.drawable.ic_dialog_alert)
//                    .setMessage(sslError)
//                    .setCancelable(false)
//                    .setNegativeButton("cancel",
//                            new DialogInterface.OnClickListener() {
//                                public void onClick(DialogInterface dialog, int which) {
//
//                                    handler.cancel();
//                                }
//                            })
//                     .setPositiveButton("ok",
//                            new DialogInterface.OnClickListener() {
//                                public void onClick(DialogInterface dialog, int which) {
//                                    handler.proceed();
//                                }
//                            })
//                     .show();
//        
//        }
    };

    /**
     * WebChromeClient implement.
     */
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            for (PageStateListener pageStateListener : mPageStateListenerList) {
                pageStateListener.onProgressChanged(newProgress);
            }
        }
    };

    @Override
    protected void onSizeChanged(int w, int h, int ow, int oh) {

        for (PageStateListener pageStateListener : mPageStateListenerList) {
            pageStateListener.onPageViewSizeChanged(w, h, ow, oh);
        }
        super.onSizeChanged(w, h, ow, oh);
    }

    /**
     * set previous url.
     *
     * @param url
     *            previous url.
     */
    public void setPrevUrl(String url) {
        mUrl = url;
    }

    /**
     * get previous url.
     *
     * @return previous url.
     */
    public String getPrevUrl() {
        return mUrl;
    }
}
